import io
import os
import urllib
from urllib.parse import urlencode

from PIL import Image
from qrcode.constants import ERROR_CORRECT_L, ERROR_CORRECT_H
from qrcode.main import QRCode


def gen_qrcode(data, logo_path="", save_path='', version=1, error_correct=ERROR_CORRECT_L,
               box_size=10, border=1):
    qr = QRCode(version=version, error_correction=error_correct, box_size=box_size, border=border)
    # img = qrcode.make("hello,world!")
    # img.save('hello.png')
    qr.add_data(data)
    # qr.make(fit=True)
    # 获得Image实例并把颜色模式转换为RGBA
    qr_img = qr.make_image()
    qr_img = qr_img.convert("RGBA")
    if logo_path and os.path.exists(logo_path):
        icon_img = Image.open(logo_path)  # 打开填充的logo文件
        img_w, img_h = qr_img.size
        # print(img_w,img_h)
        factor = 4
        # 计算logo的尺寸
        size_w = int(img_w / factor)
        size_h = int(img_h / factor)
        # 比较并重新设置logo文件的尺寸
        icon_w, icon_h = icon_img.size
        if icon_w > size_w:
            icon_w = size_w
        if icon_h > size_h:
            icon_h = size_h
        icon_img = icon_img.resize((icon_w, icon_h), Image.LANCZOS)
        # 计算logo的位置，并复制到二维码图像中
        w = int((img_w - icon_w) / 2)
        h = int((img_h - icon_h) / 2)
        icon_img = icon_img.convert("RGBA")
        qr_img.paste(icon_img, (w, h), icon_img)  # 作用为将一张图片覆盖到另一张图片的指定位置去
    if save_path:
        # 保存二维码
        qr_img.save(save_path)  # 例如qrcode.png
    file_io = io.BytesIO()
    qr_img.save(file_io, 'png')
    file_io.seek(0)
    return file_io


def decode_qrcode(qr_path):
    from pyzbar import pyzbar  # linux 需要安装 zbar shared library, 暂时跳过
    image = Image.open(qr_path)  # 打开二维码图片路径
    img_list = pyzbar.decode(image)  # 函数返回一个列表（list）的原因主要是因为它旨在处理可能包含多个条形码或二维码的图像
    for img in img_list:
        content_str = img.data.decode("utf-8")
        return urllib.parse.unquote(content_str)
    return None


if __name__ == "__main__":
    content = '你好, 世界!'
    gen_qrcode(content, logo_path='w.jpg', save_path='out.png', error_correct=ERROR_CORRECT_H, box_size=10)
    print('解析二维码: ', decode_qrcode('out.png'))
